<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use App\Model\Admin as Mod;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // session已在redis中设置有效期，有效期为120分钟
        // 默认ID存在即用户存在，
        // 每两个小时更新一次用户信息，无需每次请求都更新信息，
        // 主要目的是假如删除用户，session一直存在导致未更新
        // 此处仅判断用户是否存在，及是否有权限
        $id = (int) session()->get('admin.id');
        if (session('admin_sms_check')!=1){
            return redirect('/admin/login');
        }
        if ( !$id ) {
            if ( strpos($request->getPathInfo(), '/admin/login')!==0 ) {
                return response()->redirectTo('/admin/login')->withErrors('尚未登录！');
            }
        } else {
            // 判断请求是否合法，是否是允许操作，仅作基础判断，详细判断以方法内为准，如何不合法返回
            // 记录用户操作内容

        }
        $language = session('language');
        if (empty($language)) {
            $language = session('admin.language_id');
        }
        $language = (int) $language;
        if ($language == 1) {
            App::setLocale('en');
        } elseif ($language == 2) {
            App::setLocale('zh_tw');
        } elseif ($language == 3) {
            App::setLocale('zh');
        } else {
            $language = 3;
            App::setLocale('zh');
        }
        session(['language'=>$language]);

        $method = $request->method();
        $ip = $request->ip();
        $url = $request->url();
        $input = $request->input();
        $log = new \App\Models\OperationLogs();
        $log->user_type = 1; // member
        $log->user_id = $id;
        $log->method = $method;
        $log->ip = $ip;
        $log->url = $url;
        $log->input = @json_encode($input);
        $log->save();

        return $next($request);
    }
}
